package com.ruoyi.market.service.warning;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.block.db.entity.SmsConfigInfo;
import com.ruoyi.market.constant.RedisKeyConstent;
import com.ruoyi.market.factory.SmsInfoFactory;
import com.ruoyi.market.model.param.WarnInfoParam;
import com.ruoyi.market.model.result.SmsInfoResult;
import com.ruoyi.market.model.result.WarnInfoResult;
import com.ruoyi.market.service.ISmsInfoService;
import com.ruoyi.market.service.IWarningService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class SmsVerifyBalanceServie implements IWarningService {

    @Resource
    RedisTemplate<String, SmsConfigInfo> redisSmsConfigInfoTemplate;

    @Override
    public WarnInfoResult handleWarnInfo(WarnInfoParam warnInfoParam) {

        WarnInfoResult warnInfoResult = new WarnInfoResult();
        warnInfoResult.setTitle("sms验证码余额");

        try {
            //
            String  redisKey = RedisKeyConstent.SMS_CONFIG_INFO_VERIFY_KEY;
            Set<String> keys = redisSmsConfigInfoTemplate.keys(redisKey);

            if (CollUtil.isEmpty(keys)){
                warnInfoResult.setMessage("没有查询到相关配置");
                return warnInfoResult;
            }

            StringBuilder stringBuilder = new StringBuilder();
            for (String key : keys) {
                SmsConfigInfo smsConfigInfo = redisSmsConfigInfoTemplate.opsForValue().get(key);

                ISmsInfoService service = SmsInfoFactory.getService(smsConfigInfo.getPlatform());
                if (ObjectUtil.isEmpty(service)){
                    stringBuilder.append(smsConfigInfo.getPlatform() + "查询未实现");
                }else{
                    SmsInfoResult smsInfoResult = service.getSmsInfo(smsConfigInfo);
                    if (smsInfoResult.isSuccess()){
                        stringBuilder.append(StrUtil.format("{}({})", smsInfoResult.getBalance() , smsInfoResult.getPlatformName())).append("|");
                    }else{
                        stringBuilder.append(StrUtil.format("{}|{}({})", smsInfoResult.getCode(), smsInfoResult.getMessage() , smsInfoResult.getPlatformName())).append("|");
                    }
                }
            }

            warnInfoResult.setMessage(stringBuilder.toString());
            return warnInfoResult;
        }catch (Exception exception){
            exception.printStackTrace();
            warnInfoResult.setMessage(exception.getMessage());
        }
        return warnInfoResult;
    }
}
